package com.luo.ams.security;

import com.luo.ams.mapper.AdminMapper;
import com.luo.common.exception.BBSServiceException;
import com.luo.common.restful.ResponseCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AdminUserDetailService implements UserDetailsService {
    @Autowired
    private AdminMapper adminMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        System.out.println(s);
        AdminLoginInfoVo adminLoginInfoVo = adminMapper.getUserInfoByname(s);
        if (adminLoginInfoVo==null){
            throw new BBSServiceException(ResponseCode.NOT_FOUND,"用户不存在！");
        }
        List<String> permissions = adminLoginInfoVo.getPermissions();
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (String permission : permissions) {
            authorities.add(new SimpleGrantedAuthority(permission));
        }
        AdminUserDetails userDetails = new AdminUserDetails(
                adminLoginInfoVo.getUsername(), adminLoginInfoVo.getPassword(),adminLoginInfoVo.getEnable()==1,authorities
        );
        userDetails.setId(adminLoginInfoVo.getId());
        return userDetails;
    }
}
